package com.xiaopangzi.wsclient;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * 描述: WebSocket客户端，代替HTML中的请求实现
 * 由java-websocket组件提供
 *
 * @author : sujinchen
 * @date : 2020/9/24
 */
public class MyWebSocketClient extends WebSocketClient {
    private Logger logger = LoggerFactory.getLogger(MyWebSocketClient.class);
    private static Long total = 0L;
    private static Long succeed = 0L;
    private static Long faile = 0L;

    public static Long getTotal() {
        return total;
    }

    public static Long getSucceed() {
        return succeed;
    }

    public static Long getFaile() {
        return faile;
    }

    public MyWebSocketClient(URI serverUri) {
        super(serverUri);
    }

    public MyWebSocketClient(URI serverUri, Draft protocolDraft) {
        super(serverUri, protocolDraft);
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        short httpStatus = serverHandshake.getHttpStatus();
        String httpStatusMessage = serverHandshake.getHttpStatusMessage();
        logger.info("握手成功！握手状态：{} 握手状态信息：{}", httpStatus, httpStatusMessage);
    }

    @Override
    public void onMessage(String s) {
        logger.info("收到的消息：{}",s);
        String msg = "用户:发送命令:" + total;
        System.out.println("【msg】"+msg);
        if (s.equals(msg)) {
            succeed++;
        } else {
            faile++;
        }
        total++;
        logger.info(toString());
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        logger.info("链接已关闭！i:{},s:{},b:{}",i,s,b);
    }

    @Override
    public void onError(Exception e) {
        e.printStackTrace();
        logger.info("连接出现异常！异常信息：{}",e.getMessage());
    }

    @Override
    public String toString() {
        return "MyWebSocketClient{总请求数："+total
                +" 成功数量："+succeed
                +" 失败数量："+faile
                +"}";
    }

    public static void main(String[] args) {
        Draft_6455 draft_6455 = new Draft_6455();
        try {
            MyWebSocketClient myWebSocketClient = new MyWebSocketClient(new URI("ws://localhost:8080/myHandler"), draft_6455);
            myWebSocketClient.connect();
            while (!myWebSocketClient.getReadyState().equals(ReadyState.OPEN)) {
                System.out.println("正在连接！");
            }
            System.out.println("建立websocket连接");

            for (int i = 0; i < 10000; i++) {
                myWebSocketClient.send(i + "");
                Thread.sleep(200);

            }

        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
